<template>
  <div class="box" v-loading="bodyLoading">
    <div class="header">
      <el-card>
        <el-button
          type="primary"
          :icon="Plus"
          @click="AddFiles"
          v-hasBtn="'CreateFile'"
          >新建文件夹</el-button
        >
        <el-button
          type="info"
          :icon="Edit"
          @click="updateFiles"
          v-hasBtn="'updateFile'"
          >修改文件夹</el-button
        >
        <el-button
          type="danger"
          :icon="Delete"
          @click="deleteFiles"
          v-hasBtn="'deleteFile'"
          >批量删除</el-button
        >
      </el-card>
    </div>
    <div class="content">
      <div class="left">
        <el-card v-loading="isLoading">
          <el-tree
            style="min-height: 70vh"
            :data="fileList"
            :props="treeProps"
            @node-click="handleNodeClick"
            show-checkbox
            @check-change="getCheckedNodes"
            ref="treeRef"
            default-expand-all
            node-key="_id"
          />
        </el-card>
      </div>
      <div class="right">
        <el-card>
          <el-button
            type="primary"
            :icon="Plus"
            style="margin-bottom: 10px"
            @click="beforeUpload"
            v-hasBtn="'uploadFile'"
            >上传文件</el-button
          >
          <el-table
            style="max-width: 100%"
            :data="uploadList"
            v-loading="tableLoading"
          >
            <el-table-column
              type="index"
              align="center"
              label="序号"
              width="80"
            ></el-table-column>
            <el-table-column
              label="文件名称"
              prop="fileName"
              align="center"
            ></el-table-column>
            <el-table-column
              label="文件类型"
              prop="fileType"
              align="center"
            ></el-table-column>
            <el-table-column
              label="文件大小"
              prop="fileSize"
              align="center"
            ></el-table-column>
            <el-table-column label="创建时间" align="center">
              <template #default="{ row }">
                {{ formatDate(row.CreateAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="{ row }">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="downloadFile(row)"
                  v-hasBtn="'downloadFile'"
                  >下载</el-button
                >
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="deleteFileById(row._id)"
                  v-hasBtn="'deleteFloader'"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="page"
            v-model:current-page="pageNo"
            :page-size="10"
            layout="prev, pager, next"
            :total="total"
          />
        </el-card>
      </div>
    </div>
    <AddFile v-model="isShow" @getFileList="getFileList"></AddFile>
    <UploadFile
      v-model="uploadShow"
      v-model:parentId="parentId"
      v-model:list="uploadList"
      @getUploadList="getUploadList"
    ></UploadFile>
    <el-dialog
      v-model="updateDiglog"
      title="修改文件夹"
      width="500"
      center
      @close="closeHandler"
    >
      <el-form
        label-width="130px"
        :model="updateFile"
        ref="formRef"
        :rules="rules"
      >
        <el-form-item label="新文件夹名称:" prop="name">
          <el-input
            placeholder="请输入新的文件夹名称"
            v-model="updateFile.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="当前修改文件夹:" prop="id">
          <el-tree-select
            v-model="updateFile.id"
            :data="fileList"
            :props="treeProps"
            :check-strictly="true"
          >
          </el-tree-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeHandler">取消</el-button>
          <el-button type="primary" @click="SaveFiles"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  deleteFileAPI,
  deleteFileByIDAPI,
  getFileListAPI,
  getFileListByIDAPI,
  updateFileAPI,
} from "@/api/file";
import { buildTree } from "@/utiles/tree";
import AddFile from "./AddFile/index.vue";
import UploadFile from "./uploadFile/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { downloadFileWithAxios, formatDate } from "@/utiles/time";
import axios from "axios";
let fileList = ref([]);
let treeRef = ref(null);
let isShow = ref(false);
let treeProps = {
  label: "name",
  children: "children",
  value: "_id",
};
let formRef = ref(null);
let updateFile = reactive({
  id: "",
  name: "",
});
let bodyLoading = ref(false);
let isLoading = ref(false);
let updateDiglog = ref(false);
let seletcTreeNode = ref([]);
let uploadList = ref([]);
let pageNo = ref(1);
let total = ref(0);
let fileName = ref("");
let tableLoading = ref(false);
let uploadShow = ref(false);
let parentId = ref("");
//表单校验
const validataName = (rule, value, callback) => {
  const regex = /^[a-zA-Z0-9\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5_. ]*$/;

  if (regex.test(value)) {
    callback();
  } else {
    callback(new Error("文件夹名称格式错误"));
  }
};
let rules = reactive({
  name: [
    { required: true, message: "请输入文件夹名称", trigger: "blur" },
    {
      validator: validataName,
      message: "文件夹名称格式错误",
      trigger: "blur",
    },
  ],
  id: [{ required: true, message: "请选择要修改的文件夹", trigger: "blur" }],
});
onMounted(() => {
  getFileList();
});
const getFileList = async () => {
  isLoading.value = true;
  let result = await getFileListAPI();
  let tree = buildTree(result.data);
  fileList.value = tree;
  isLoading.value = false;
};
const getUploadList = async (parentId) => {
  tableLoading.value = true;
  let result = await getFileListByIDAPI(parentId, fileName.value, pageNo.value);
  uploadList.value = result.data.result;
  total.value = result.data.total;
  tableLoading.value = false;
};
const handleNodeClick = (data) => {
  getUploadList(data._id);
  parentId.value = data._id;
};
const closeHandler = () => {
  formRef.value.resetFields();
  updateFile.id = "";
  updateFile.name = "";
  updateDiglog.value = false;
};
const AddFiles = () => {
  isShow.value = true;
};
const getCheckedNodes = (data) => {
  seletcTreeNode.value = treeRef.value.getCheckedKeys();
};
const updateFiles = () => {
  updateDiglog.value = true;
};
const SaveFiles = async () => {
  await formRef.value.validate();
  let result = await updateFileAPI(updateFile);
  if (result.code === 200) {
    ElMessage.success("修改成功");
    closeHandler();
    getFileList();
  }
};
const deleteFiles = async () => {
  if (seletcTreeNode.value.length === 0) {
    ElMessage.warning("请选择要删除的文件夹");
    return;
  }
  if (seletcTreeNode.value.length > 4) {
    ElMessage.warning("一次最多只能删除4个文件夹");
    return;
  }
  ElMessageBox.prompt("请输入你的账户密码:", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputType: "password",
  })
    .then(async ({ value }) => {
      let isSuccess = false;
      // 使用map创建Promise数组，每个Promise对应一个文件删除操作
      const deletePromises = seletcTreeNode.value.map(async (item) => {
        try {
          let result = await deleteFileAPI(item, { password: value });
          if (result?.code == 200) {
            isSuccess = true;
          } else {
            isSuccess = false;
          }
        } catch (error) {
          // 捕获API调用中的错误
          ElMessage.error(
            `删除文件 ${item.name || item.id} 时发生错误: ${error.message}`
          );
        }
      });

      // 等待所有删除操作完成
      await Promise.all(deletePromises);

      // 所有操作完成后，显示全局的“删除成功”消息并获取新的文件列表
      if (isSuccess) {
        ElMessage.success("文件删除成功");
        getFileList();
      }
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};
const beforeUpload = () => {
  if (parentId.value === "") {
    ElMessage.warning("请选择文件夹");
    return;
  } else {
    uploadShow.value = true;
  }
};
const downloadFile = (row) => {
  bodyLoading.value = true;
  axios({
    method: "get",
    url: "http://" + row.filePath,
    responseType: "blob", // 告诉axios我们期望返回的是blob
  })
    .then((response) => {
      // 创建一个Blob对象，这里response.data就是服务器返回的blob数据
      const blob = new Blob([response.data], {
        type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      }); // 根据你的文件类型设置MIME类型

      // 创建一个指向blob对象的URL
      const url = window.URL.createObjectURL(blob);

      // 创建一个a标签用于下载
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", row.fileName); // 设置下载文件名
      document.body.appendChild(link);

      // 触发点击
      link.click();

      // 然后移除这个元素
      document.body.removeChild(link);

      // 释放URL对象
      window.URL.revokeObjectURL(url);
      bodyLoading.value = false;
    })
    .catch((error) => {
      ElMessage.error("文件下载失败");
    });
};
const deleteFileById = async (id) => {
  bodyLoading.value = true;
  let result = await deleteFileByIDAPI(id);
  if (result?.code == 200) {
    ElMessage.success("删除成功");
    getUploadList(parentId.value);
  }
  console.log(111);
  bodyLoading.value = false;
};
</script>

<style lang="scss" scoped>
.box {
  .header {
    margin-bottom: 10px;
  }
  .content {
    display: flex;
    .left {
      flex: 2;
    }
    .right {
      flex: 8;
      margin-left: 10px;
      .page {
        display: flex;
        justify-content: center;
        margin-top: 10px;
      }
    }
  }
}
</style>
